package com.ls.utils.sms;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ls.base.BaseResult;
import com.ls.exception.SysException;
import com.ls.utils.ResultData;
import com.ls.utils.http.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by pengyu on 2020/4/6.
 * 短信平台调用方法
 */
@Slf4j
public class SmsPyUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(SmsPyUtil.class);

    //预留6个字符来做签名```20201127 现在不预留字符做签名了。
    public static final int MAX_CONTENT = 65;
    public static final int MAX_LONG_CONTENT = MAX_CONTENT * 2;
    public static final int MAX_CONTENT_2021 = 500;

    private static final String URL = "http://203.6.230.96:8084/smsRecord/sendSms";
    private static final String GETURL = "http://203.6.230.96:8084/smsRecord/getStatusByRecordId";

    public static ResultData sendCommonSms(SendSmsModel model) throws IOException {
        LOGGER.info("sendCommonSms发送短信:" + model.toString());
        if(model==null){
            throw new SysException("sendCommonSms model 为 null ");
        }
        BaseResult baseResult = null;
        String content = model.getContent();
        if(content.length() >= MAX_CONTENT_2021){
            throw new SysException("短信长度不能超过"+ MAX_CONTENT_2021 +"，请联系管理员 ");
        }
        baseResult = sendSmsJson(model);
        log.info("发送结果:{}" + JSON.toJSONString(baseResult));
        return ResultData.convertBaseResultToResult(baseResult);
    }
    public static ResultData getSmsStatus(Long recordId) throws IOException {
        if (recordId == null || recordId <= 0) {
            throw new SysException("短信记录ID不能为空");
        }
        String fullUrl = GETURL + "?recordId=" + recordId;
        String postResult = HttpUtils.sendSyncGet(fullUrl);

        if (postResult == null) {
            throw new SysException("获取短信状态接口无响应");
        }

        BaseResult baseResult = JSON.parseObject(postResult, BaseResult.class);
        if (baseResult == null) {
            throw new SysException("短信状态解析失败");
        }

        return ResultData.convertBaseResultToResult(baseResult);
    }

    public static ResultData sendValidSms(SendSmsModel model) throws IOException {
        LOGGER.info(model.toString());
        if(model==null){
            throw new SysException("sendValidSms model 为 null ");
        }
        //校验缓存中是否存在验证码
        String validCode = model.getValidCode();
        if(StringUtils.isBlank(validCode)){
            throw new SysException("sendValidSms 生成校验码失败，请联系管理员 ");
        }

//        String key = LOGIN_PREFIX + model.getMobile();
//        Object obj = LocalCache.get(key);
//        if(obj!=null){
//            log.error("手机号码{}重复发送验证码,缓存中为{}",model.getMobile(),obj);
//            throw new SysException(DEFAULT_TIME_MINUTE+"分钟内请勿重复发送验证码 ");
//        }
//        String str =  JSONObject.toJSONString(model);
//        String postResult = HttpUtils.sendPost(URL,str);
//        //验证码放入缓存 不在这个类里面做 可以考虑 改造成 Redis
//        LocalCache.set(LOGIN_PREFIX + model.getMobile() ,model.getValidCode(),DEFAULT_TIMEOUT);\

        String str =  JSONObject.toJSONString(model);
        String postResult = HttpUtils.sendPost(URL,str);
        if(postResult==null){
            throw new SysException("sendValidSms 远程调用短信平台接口返回 null，请联系管理员 ");
        }
        BaseResult baseResult = JSON.parseObject(postResult, BaseResult.class);
        if(baseResult == null){
            throw new SysException("sendValidSms 远程调用短信平台接口返回值解析为 null，请联系管理员 ");
        }
        return ResultData.convertBaseResultToResult(baseResult);
    }

    private static BaseResult sendSmsJson(SendSmsModel model) throws IOException {
        String str =  JSONObject.toJSONString(model);
        String postResult = HttpUtils.sendPost(URL,str);
        log.info("发送结果postResult:{}" + JSON.toJSONString(postResult));
        if(postResult==null){
            log.error("sendCommonSms postResult==null 远程调用短信平台接口返回 null，请联系管理员 model ="+model.toString());
            throw new SysException("sendCommonSms 远程调用短信平台接口返回 null，请联系管理员 ");
        }
        BaseResult baseResult = JSON.parseObject(postResult, BaseResult.class);
        log.info("发送结果baseResult:{}" + JSON.toJSONString(baseResult));
        if(baseResult == null){
            log.error("sendCommon SmsbaseResult == null  远程调用短信平台接口返回值解析为 null，请联系管理员 model ="+model.toString());
            throw new SysException("sendCommonSms 远程调用短信平台接口返回值解析为 null，请联系管理员 ");
        }
        return baseResult;
    }

    private static List<String> stringSpilt(String str,int len) {
        String strStart = str.substring(0,len);
        String strSub = str.substring(len,str.length());
        List<String> list = new ArrayList<>(2);
        list.add(strStart);
        list.add(strSub);
        return list;
    }

    public static void main(String[] args) throws IOException {
        SendSmsModel sendSmsModel  = new SendSmsModel("19960511416","欢迎致电随信通","19960511416");
        ResultData result = SmsPyUtil.sendCommonSms(sendSmsModel);
        log.info("短信发送结果:={}", JSON.toJSONString( result));
    }
}
